import React from 'react'
import { Link } from 'react-router-dom';
import { InputNumber, DatePicker, Select, Upload, Tooltip, Modal, Icon, Popconfirm, Table, Col, Row, Form, Input, Button, Message } from 'antd';
import api from '../../../api/LossPrevention';
import md5 from 'md5';
import moment from 'moment';
import serverConfig from "../../../utils/config";
import { reqToken } from "../../../utils/reqTools";
import PanelBox from '../../../components/PanelBox';
import './index.less';

const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;
const pageRouter = '/agent/LossPrevention';

class SearchClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {//第二步，赋初始值
      loading: false,
    };
  }
  static defaultProps = {
    onSearch: function (params) { }
  };
  setObjectState = (key, value) => {
    let keyArray = key.split("\.");
    let first = keyArray[0];
    let o = this.state[first];
    let level = o;
    for (let i = 1; i < keyArray.length; i++) {
      let ele = keyArray[i];
      level = o[ele];
    }
    for (let ele in value) {
      if (value.hasOwnProperty(ele)) {
        level[ele] = value[ele];
      }
    }
    let r = {};
    r[first] = o;
    this.setState(r);
  }
  onSubmit = (e) => {
    e.preventDefault();
    let params = this.props.form.getFieldsValue();
    if (params.dateBetween) {
      params.createDateBegin = moment(params.dateBetween[0]).format("YYYY-MM-DD HH:mm:ss");
      params.createDateEnd = moment(params.dateBetween[1]).format("YYYY-MM-DD HH:mm:ss");
    }
    this.props.onSearch(params);
  }
  componentDidMount() {
  }
  componentWillReceiveProps = nextProps => {
  }
  onDownload = () => {
    let params = this.props.form.getFieldsValue();
    if (params.dateBetween) {
      params.createDateBegin = moment(params.dateBetween[0]).format("YYYY-MM-DD HH:mm:ss");
      params.createDateEnd = moment(params.dateBetween[1]).format("YYYY-MM-DD HH:mm:ss");
    }
    this.props.onDownload(params);
  }
  onBuy = () => {
    let params = this.props.form.getFieldsValue();
    if (params.dateBetween) {
      params.createDateBegin = moment(params.dateBetween[0]).format("YYYY-MM-DD HH:mm:ss");
      params.createDateEnd = moment(params.dateBetween[1]).format("YYYY-MM-DD HH:mm:ss");
    }
    this.props.onBuy(params);
  }
  onMark = (value) => {
    let params = this.props.form.getFieldsValue();
    if (params.dateBetween) {
      params.createDateBegin = moment(params.dateBetween[0]).format("YYYY-MM-DD HH:mm:ss");
      params.createDateEnd = moment(params.dateBetween[1]).format("YYYY-MM-DD HH:mm:ss");
    }
    this.props.onMark(params, value);
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const layout = {
      searchItem: {
        span: 5
      },
      lable: {
        span: 7
      },
      content: {
        span: 15
      }
    }
    return (
      <Form onSubmit={this.onSubmit}>
        <Row className="search-box" type="flex" justify="start">
          <Col {...layout.searchItem} className="search-item">
            <Col {...layout.lable} className="label">用户姓名</Col>
            <Col {...layout.content} className="content" >
              {getFieldDecorator('userName', {
              })(
                <Input placeholder="模糊匹配用户姓名" />
                )}
            </Col>
          </Col>
          <Col {...layout.searchItem} className="search-item">
            <Col {...layout.lable} className="label">信息填充</Col>
            <Col {...layout.content} className="content" >
              {getFieldDecorator('isFill', {
              })(
                <Select
                  placeholder="信息是否填充"
                  onChange={this.handleSelectChange}
                >
                  <Option value="1">是</Option>
                  <Option value="0">否</Option>
                </Select>
                )}
            </Col>
          </Col>
          <Col {...layout.searchItem} className="search-item">
            <Col {...layout.lable} className="label">信息标记</Col>
            <Col {...layout.content} className="content" >
              {getFieldDecorator('isLoad', {
              })(
                <Select
                  placeholder="已使用或未使用"
                  onChange={this.handleSelectChange}
                >
                  <Option value="0">未使用</Option>
                  <Option value="1">已使用</Option>
                </Select>
                )}
            </Col>
          </Col>
          <Col span="8" className="search-item">
            <Col span="5" className="label">创建时间</Col>
            <Col span="18" className="content" >
              {getFieldDecorator('dateBetween', {
              })(
                <RangePicker format="YYYY/MM/DD HH:mm:ss" showTime={
                  {
                    hideDisabledOptions: false,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
                  }
                } />
                )}
            </Col>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="search" htmlType="submit">搜索</Button>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="reload" onClick={() => this.props.form.resetFields()}>清空</Button>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="download" onClick={this.onDownload.bind(this)}>下载</Button>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="check" onClick={this.onMark.bind(this, 0)}>标记为已使用</Button>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="close" onClick={this.onMark.bind(this, 1)}>标记为未使用</Button>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="pay-circle" onClick={this.onBuy.bind(this)}>购买</Button>
          </Col>
        </Row>
      </Form>
    );
  }
}

const Search = Form.create()(SearchClass);

class BuyFormClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }
  componentDidMount = () => {
  }
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.clear && nextProps.clear != this.props.clear) {
      this.props.form.resetFields();
    }
  }
  constants = {
    buttonLayout: {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        }
      }
    },
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
  }
  onSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return false;
      }
      api.post('/buy', values).then(res => {
        this.props.onSubmit && this.props.onSubmit(res);
      });
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = this.constants.formItemLayout;
    const tailFormItemLayout = this.constants.buttonLayout;
    return (
      <Form className="form" onSubmit={this.onSubmit}>
        <FormItem
          {...formItemLayout}
          label="购买数量"
          hasFeedback
        >
          {getFieldDecorator('num', {
            rules: [{ required: true, message: '购买数量不能为空' },
            { pattern: /^\d+$/, message: '购买数量只能是正整数' }],
          })(
            <InputNumber className="inputNumber" min={1} max={10000} placeholder="需要购买的数量,一次最多10000个" />
            )}
        </FormItem>
        <FormItem {...tailFormItemLayout}>
          <Button className="button" loading={this.state.loading} size="large" type="primary" htmlType="submit">提交</Button>
          <Button className="button" onClick={this.props.onCancel}>取消</Button>
        </FormItem>
      </Form>
    );
  }
}

const BuyForm = Form.create()(BuyFormClass);

export default class TableClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      pagination: {
        pageSize: 10
      },
      showBuyModal: false,
      downloadUrl: null,
      loading: false,
      searchParams: {
      }
    }
  }
  setObjectState = (key, value) => {
    let keyArray = key.split("\.");
    let first = keyArray[0];
    let o = this.state[first];
    let level = o;
    for (let i = 1; i < keyArray.length; i++) {
      let ele = keyArray[i];
      level = o[ele];
    }
    for (let ele in value) {
      if (value.hasOwnProperty(ele)) {
        level[ele] = value[ele];
      }
    }
    let r = {};
    r[first] = o;
    this.setState(r);
  }
  handleTableChange = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setObjectState("pagination", pager);
    this.fetch({
      ...this.searchParams,
      pageSize: pagination.pageSize,
      pageNum: pagination.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  }
  fetch = (params) => {
    if (!params) {
      params = { ...this.searchParams };
    }
    if (!params.pageNum) {
      params.pageNum = 1;
    }
    params.pageSize = this.state.pagination.pageSize;
    this.searchParams = { ...params };
    this._isMounted && this.setState({ loading: true });
    api.get('/findPage', { ...params }).then(res => {
      const data = res.data || [];
      const pagination = this.state.pagination;
      pagination.current = params.pageNum;
      pagination.total = data.total;
      this._isMounted && this.setState({
        loading: false,
        data: data.list,
        pagination,
      });
    }).catch(e => {
      this._isMounted && this.setState({
        loading: false
      });
      Message.error("发生网络错误,code:" + e.response.status);
    });
  }
  componentWillMount() {
    this._isMounted = true;
    reqToken().then(res => {
      this.downloadUrl = serverConfig.primary + '/api/QrUserInfo/download?token=' + res
    });
  }
  componentWillUnmount() {
    this._isMounted = false;
  }
  componentDidMount() {
    this.fetch();
  }
  componentWillReceiveProps = nextProps => {
    if (nextProps.record != this.props.record) {
      this.props.form.resetFields();
      this.setObjectState("pagination", { current: 1, });
      this._isMounted && this.setState({
        params: {
          infoId: nextProps.record.id,
          structureId: nextProps.record.structureId
        }
      });
      this.search.params = {
        infoId: nextProps.record.id,
        structureId: nextProps.record.structureId
      }
      this.fetch();
    }
  }
  onSearch = (params) => {
    this.fetch(params);
  }
  onMark = (params, value) => {
    api.put('/mark', { ...params, state: value }).then(res => {
      if (res.code == 0) {
        Message.success("操作成功");
        this.fetch();
      } else {
        Message.error(res.message);
      }
    }).catch(e => {
      Message.error(e.response.data.error + "(code:" + e.response.data.status + ")");
    });
  }
  onDownload = (params) => {
    let str = "";
    for (let i in params) {
      if (params[i] != undefined) {
        str += "&" + i + "=" + params[i];
      }
    }
    window.location.href = this.downloadUrl + str;
  }
  onBuy = (params) => {
    this.setState({
      showBuyModal: true,
    });
  }
  onBuySubmit = (params) => {
    if (params.code == 0) {
      Message.success("购买成功");
      this.setState({
        showBuyModal: false
      });
    }else{
      Message.error(params.message);
    }
  }
  onBuyCancel = (params) => {
    this.setState({
      showBuyModal: false,
    });
  }
  render() {
    let columns = [{
      title: '防丢URL地址',
      dataIndex: 'id',
      width: '50%',
      render: function (text, record, index) {
        return text;
      }
    }, {
      title: '用户姓名',
      dataIndex: 'userName',
      width: '30%',
      render: function (text, record, index) {
        return text || '未填充用户信息';
      }
    }, {
      title: '创建时间',
      dataIndex: 'createDate',
      width: '20%',
      render: function (text, record, index) {
        return moment(text).format("YYYY/MM/DD HH:mm:ss");
      }
    }];
    return (
      <div>
        <Search onSearch={this.onSearch} onMark={this.onMark} onDownload={this.onDownload} onBuy={this.onBuy} />
        <Table columns={columns}
          rowKey={"id"}
          dataSource={this.state.data}
          pagination={this.state.pagination}
          loading={this.state.loading}
          onChange={this.handleTableChange}
        />
        {<Modal
          title="购买"
          visible={this.state.showBuyModal}
          maskClosable={false}
          onCancel={this.onBuyCancel}
          wrapClassName="vertical-center-modal"
          width="500"
          style={{ height: 'auto' }}
          footer={null}
        >
          <BuyForm clear={this.state.showBuyModal} onCancel={this.onBuyCancel} onSubmit={this.onBuySubmit}/>
        </Modal>}
      </div>
    );
  }
}







